package com.tyut.controller;

import com.tyut.pojo.Remark;
import com.tyut.pojo.Travel;
import com.tyut.service.RemarkService;
import com.tyut.service.TravelService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

@Controller
public class RemarkController {
    @Resource
    private RemarkService remarkService;

    @Resource
    private TravelService travelService;

    /**
     * 查询所有的评论
     * @return
     */
    @RequestMapping("/queryListRemarkByTid/{tid}")
    @ResponseBody
    public List<Remark> queryListRemarkByTid(@PathVariable("tid") int tid, HttpServletResponse response){
        response.setHeader("Access-Control-Allow-Origin","*");
        List<Remark> remarks = remarkService.queryListRemarkByTid(tid);
//        System.out.println(remarks);
        return remarks;
    }

    /**
     * 添加评论
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/addRemark")
    @ResponseBody
    public String addRemark(HttpServletRequest request, HttpServletResponse response){
        response.setHeader("Access-Control-Allow-Origin","*");

        System.out.println("request"+request);
        float rscore = Float.parseFloat(request.getParameter("rscore"));
        String rtext = request.getParameter("rtext");
        int  cid = Integer.parseInt(request.getParameter("cid"));
        int tid = Integer.parseInt(request.getParameter("tid"));
        Date date = new Date();

        Remark remark = new Remark();
        remark.setRscore(rscore);
        remark.setRtext(rtext);
        remark.setRtime(date);
        remark.setCid(cid);
        remark.setTid(tid);

        System.out.println("remark"+remark);

        boolean flag = remarkService.addRemark(remark);
        System.out.println("debug==>flag:"+flag);
        if (flag) {
            float tscore = travelService.queryTravelById(tid).getTscore();
            System.out.println("debug==>tscore:"+tscore);
            Travel travel = new Travel();
            travel.setTscore((rscore + tscore )/ 2);
            travel.setTid(tid);
            System.out.println("debug==>score:"+travel.getTscore());
            travelService.updateTravel(travel);
            return "true";
        }
        return "false";
    }

    /**
     *
     * @param cid
     * @param response
     * @return
     */
    @RequestMapping("/deleteRemark/{cid}")
    @ResponseBody
    public boolean deleteRemark(@PathVariable("cid") Integer cid, HttpServletResponse response){
        response.setHeader("Access-Control-Allow-Origin","*");
        return remarkService.deleteRemark(cid);
    }



}
